from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from luffyapi.utils.serializers import BaseSerializers
from . import models
import re
from django.core.cache import cache
from django.conf import settings


class UserSerilaizer(BaseSerializers):
    username = serializers.CharField()

    class Meta:
        model = models.User
        fields = ['username', 'password', 'id']
        extra_kwargs = {
            'id': {"read_only": True},
            'password': {"write_only": True},
        }

    def validate(self, attrs):
        attrs = self.login(attrs)
        return attrs

    def _get_user(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')
        if re.match('^1[3-9][0-9]{9}$', username):
            user = models.User.objects.filter(telephone=username).first()
        elif re.match('^.+@.+$', username):
            user = models.User.objects.filter(email=username).first()
        else:
            user = models.User.objects.filter(username=username).first()
        if user:
            ret = user.check_password(password)
            if ret:
                return user
            else:
                raise ValidationError('密码错误')
        else:
            raise ValidationError('用户不存在')




class CodeUserSerilaizer(BaseSerializers):
    code = serializers.CharField()

    class Meta:
        model = models.User
        fields = ['telephone', 'code']

    def validate(self, attrs):
        attrs = self.login(attrs)
        return attrs

    def _get_user(self, attrs):
        telephone = attrs.get('telephone')
        code = attrs.get('code')
        if re.match('^1[3-9][0-9]{9}$', telephone):
            user = models.User.objects.filter(telephone=telephone).first()
            if user:
                cache_code=cache.get(settings.PHONE_CACHE_KEY%telephone)
                if cache_code==code:
                    cache.set(settings.PHONE_CACHE_KEY % telephone, '')
                    return user
                else:
                    raise ValidationError('验证码错误')
            else:
                raise ValidationError('用户不存在')
        else:
            raise ValidationError('手机号格式错误')



class UserRegisterSerilaizer(BaseSerializers):
    code = serializers.CharField(write_only=True)
    class Meta:
        model = models.User
        fields = ['telephone', 'code', 'password', 'username']
        extra_kwargs = {
            'password': {'max_length': 18, 'min_length': 8},
            'username': {'read_only': True}
        }

    def validate(self, attrs):
        telephone = attrs.get('telephone')
        code = attrs.get('code')
        # 取出原来的code

        if re.match('^1[3-9][0-9]{9}$', telephone):
            cache_code = cache.get(settings.PHONE_CACHE_KEY % telephone)
            if code == cache_code:
                attrs['username'] = telephone  # 把用户的名字设成手机号
                attrs.pop('code')
                return attrs
            else:
                raise ValidationError('验证码错误')
        else:
            raise ValidationError('手机号不合法')


    # 重写create方法
    def create(self,validated_data):
        user = models.User.objects.create_user(**validated_data)
        return user

